<template>
  <div>
    <div class="absolute left-1/2 bottom-10" style="z-index: 999; transform: translate(-50%, -50%)">
      <button class="button" data-text="Awesome" @click="open()">
        <span class="actual-text">&nbsp;Enter&nbsp;Code&nbsp;</span>
        <span aria-hidden="true" class="hover-text">&nbsp;Enter&nbsp;Code&nbsp;</span>
      </button>
    </div>
    <!-- <div class="absolute left-0 top-0 w-30" style="z-index: 90; height: 100vh; overflow: auto" v-show="zsdlist">
      <el-tag size="small" :color="getRandomColor()" class="ml-2 mt-2 w-20" effect="dark"
        @click="loadData()">全部</el-tag>
      <el-tag size="small" :color="getRandomColor()" class="ml-2 mt-2 w-20" effect="dark" v-for="o2 in zsdlist"
        :key="o2" @click="tagfilter(o2)">{{ o2 }}</el-tag>
    </div> -->
    <!-- <div class="code-editor float-left m-2" v-for="(o, i) in list" :key="o[id]">
      <div class="header">
        <span class="title">{{ o.title }}</span>
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" class="icon">
          <g stroke-width="0" id="SVGRepo_bgCarrier"></g>
          <g stroke-linejoin="round" stroke-linecap="round" id="SVGRepo_tracerCarrier"></g>
          <g id="SVGRepo_iconCarrier">
            <path stroke-linecap="round" stroke-width="2" stroke="#4C4F5A" d="M6 6L18 18"></path>
            <path stroke-linecap="round" stroke-width="2" stroke="#4C4F5A" d="M18 6L6 18"></path>
          </g>
        </svg>
      </div>
      <div class="editor-content" ref="codeBlock">
        <highlightjs autodetect :code="o.code" class="text-left overflow-auto break-all" />
      </div>
    </div> -->
    <div class="overflow-auto" style="height: 100vh">
      <div class="masonry">
        <div class="item" v-for="(o, i) in list" :key="o[id]">
          <aside class="card2 bg-black text-white p-6 rounded-lg w-full max-w-lg font-mono">
            <div class="flex justify-between items-center">
              <div class="flex space-x-2 text-red-500">
                <el-tooltip class="box-item" effect="dark" content="删除" placement="top">
                  <div class="w-3 h-3 rounded-full bg-red-500" @click="del(o.id)"></div>
                </el-tooltip>
                <el-tooltip class="box-item" effect="dark" content="复制" placement="top">
                  <div class="w-3 h-3 rounded-full bg-yellow-500" @click="cp(o)"></div>
                </el-tooltip>

                <el-tooltip class="box-item" effect="dark" content="修改" placement="top">
                  <div class="w-3 h-3 rounded-full bg-green-500" @click="openedit(o)"></div>
                </el-tooltip>
              </div>
              <div style="font-size: 10px" class="text-right text-blue-500">{{ formatDate(o.time) }}</div>
            </div>

            <div class="mt-4">
              <img :src="`https://zt-1304966785.cos.ap-nanjing.myqcloud.com/` + o.language + `.png`"
                class="w-8 h-8 float-left" />
              <div class="w-3/4 float-left">
                <p class="text-sm text-white text-left pl-2">{{ o.title }}</p>
              </div>
              <p class="text-green-400 text-left pl-10">
                <!-- ✈ {{ capitalizeFirstLetter(o.language) }} -->

                <svg v-if="o.jx" @click="openjx(o)" t="1712557313025" class="icon float-right" viewBox="0 0 1029 1024"
                  version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="7859" width="20" height="20">
                  <path
                    d="M513.128884 0.000513a512 512 0 1 0 511.281619 513.128884v-0.718381A511.28162 511.28162 0 0 0 513.744638 0.000513z m28.735217 694.673883l-36.124273-85.282021H365.245139l-36.124273 85.282021h-92.363199L389.977951 324.195342h90.515936l153.32291 370.479054z m210.998597 0h-78.919222v-370.479054h78.919222z"
                    fill="#FF5E34" p-id="7860"></path>
                  <path d="M382.999399 543.096123H488.498697l-52.749649-129.411104z" fill="#FF5E34" p-id="7861"></path>
                </svg>
              </p>
              <div style="clear: both"></div>
              <div class="text-left mt-4">
                <el-tag size="small" :color="getRandomColor()" class="ml-2 mt-2" effect="dark"
                  v-for="o2 in getSplitResult(o.zsd)" :key="o2">{{ o2 }}</el-tag>
              </div>
              <!-- <p class="text-white">+ next@10.2.3</p>
            <p class="text-white">added 1 package, and audited 2 packages in 3s</p>
            <p class="text-green-400">$</p> -->
              <highlightjs autodetect :code="o.code" class="text-left overflow-auto break-all" />
            </div>
          </aside>
        </div>
      </div>
    </div>
    <el-drawer v-model="drawer2" title="I am the title" size="40%" :with-header="false" custom-class="bg-black">
      <div class="p-2 text-left" v-html="getMdiText(aifx2)"></div>
    </el-drawer>
    <el-drawer v-model="drawer" title="I am the title" size="40%" :with-header="false" custom-class="bg-black"
      @open="opendarwer()">
      <div @keydown.ctrl.83="save">
        <el-input v-model="title" placeholder="请输入代码片段标题" size="large" class="input-with-select">
          <template #prepend>
            <el-button @click="fx">
              <el-icon>
                <svg t="1712415340803" class="icon" viewBox="0 0 1024 1024" version="1.1"
                  xmlns="http://www.w3.org/2000/svg" p-id="3298" width="200" height="200">
                  <path
                    d="M0 0m204.8 0l614.4 0q204.8 0 204.8 204.8l0 614.4q0 204.8-204.8 204.8l-614.4 0q-204.8 0-204.8-204.8l0-614.4q0-204.8 204.8-204.8Z"
                    fill="#101010" p-id="3299"></path>
                  <path
                    d="M585.216 833.3312v-375.808a119.4496 119.4496 0 0 1 119.3984 119.3472v256.4096z m-423.8336-8.8576v-605.4912h121.1392v605.4912z m121.8048-247.6032v-119.3472h302.08v35.1232a84.3264 84.3264 0 0 1-84.3776 84.224z m149.248-119.3472l103.6288-242.3296h133.4272l-79.9232 186.88a91.2896 91.2896 0 0 1-83.968 55.4496z"
                    fill="#FFFFFF" p-id="3300"></path>
                  <path
                    d="M862.5664 260.9152a70.2464 70.2464 0 0 1-70.2464 70.2464c-10.24 0-64.9728 7.0144-64.9728 7.0144s10.5472-12.288 19.3024-23.8592a70.2464 70.2464 0 1 1 115.8656-53.3504z"
                    fill="#017AFD" p-id="3301"></path>
                </svg>
              </el-icon>
            </el-button>
          </template>
          <template #append>
            <el-select v-model="language" placeholder="Select" style="width: 115px">
              <el-option label="javascript" value="javascript" />
              <el-option label="csharp" value="csharp" />
              <el-option label="html" value="html" />
              <el-option label="css" value="css" />
              <el-option label="java" value="java" />
              <el-option label="mysql" value="mysql" />
              <el-option label="sql" value="sql" />
              <el-option label="pytho" value="python" />
              <el-option label="xml" value="xml" />
              <el-option label="json" value="json" />
              <el-option label="bat" value="bat" />
            </el-select>
          </template>
        </el-input>
        <div class="text-left" v-show="titlefx">
          <el-tag size="small" :color="getRandomColor()" class="ml-2 mt-2" effect="dark" v-for="(o, i) in taglist"
            closable @close="tagClose(i)" :key="o">{{ o }}</el-tag>
        </div>
      </div>
      <div class="card2 text-left mt-2">
        <CodingEditor v-model="value" :language="language" class="text-left" height="400px" />
      </div>
      <div class="card2 text-left mt-2">
        <!-- <div class="p-2" v-html="getMdiText(aifx)"></div> -->
        <div id="vditor" ref="vditor"></div>
      </div>
      <div class="h-20"></div>

      <svg v-loading="loading" t="1712417182454" class="abs icon rotate" @click="change" viewBox="0 0 1089 1024"
        version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="19592" id="mx_n_1712417182454" width="50" height="50">
        <path
          d="M466.63477617 31.24645905c61.12522043 0.88373813 118.42090898 24.45008817 165.40631938 71.43549856 6.92261532 6.92261532 12.96149253 8.54280189 22.24074285 7.21719472 134.77006433-19.00036972 253.04368363 66.13306981 277.78835118 200.01939602 6.48074626 35.20223538 4.41869063 70.25718107-5.59700813 104.57567833-2.50392469 8.3955122-0.88373813 13.69794096 4.56598031 20.32597691 111.49829366 136.83211996 44.7760651 343.77413131-125.63810368 388.84477577-9.72111939 2.50392469-13.99252034 6.92261532-17.38018316 15.75999661-63.33456576 164.66987094-276.02087492 209.00406699-400.03879204 83.36596328-6.1861669-6.1861669-11.48859565-7.51177407-19.88410786-6.33345656-136.68483027 19.2949491-255.10573925-65.98578013-279.55582743-201.34500323-6.33345658-34.7603663-3.97682157-69.37344294 6.03887721-103.25007113 2.50392469-8.3955122 0.88373813-13.69794096-4.41869062-20.32597692-111.94016272-136.97940963-44.03961664-345.39431787 126.96371087-389.28664484 8.54280189-2.20934532 12.51962347-5.89158752 15.6127069-13.84523064 36.82242196-96.32745582 126.22726243-157.59996593 233.89602422-157.15809688z m148.17342591 593.13557275c-77.32708608 44.6287754-152.1502475 87.49007455-226.38425013 131.08782212-16.79102442 9.86840908-31.07812413 9.5738297-47.86914855-0.29457938-58.17942668-34.46578693-116.80072242-67.90054606-175.42201815-101.48259488-4.27140094-2.35663501-7.80635344-7.2171947-14.58167908-5.15513907-7.95364315 71.58278827 14.4343894 131.23511182 73.20297482 173.50725221 59.2104545 42.56671978 124.3124965 47.86914853 188.82537976 13.69794097 65.98578013-34.907656 129.76221494-74.08671296 194.42238788-111.49829366 3.68224221-2.06205563 7.80635344-3.68224221 7.80635345-9.13196065v-90.73044766z m-41.24111259-487.38157692c-1.47289687-5.15513907-5.30242877-6.62803595-8.24822251-8.69009157-58.91587511-39.9155054-121.66128212-46.24896197-185.29042725-14.87625848-64.21830387 31.81457257-98.38951143 86.16446736-100.30427737 157.89454531-1.91476594 72.90839547-0.29457937 145.81679091-0.73644845 218.72518637 0 7.80635344 2.65121438 11.93046471 9.27925032 15.46541723 21.65158411 11.93046471 43.00858883 24.59737787 64.36559358 36.82242194 2.65121438 1.47289687 5.0078494 4.71327001 9.42654001 1.91476595 0-86.31175705 0.29457937-173.06538315-0.14728967-259.81900928-0.1472897-17.82205222 6.62803595-29.31064787 22.09345315-38.00073943 44.7760651-25.18653662 89.11026111-51.10952167 133.59174684-76.88521704 18.70579035-10.75214722 37.4115807-21.79887379 55.97008135-32.551021z m85.28072925 341.56478599v18.85308004c0 81.89306641-0.1472897 163.93342252 0.14728967 245.82648892 0.1472897 16.64373472-6.03887719 27.98504069-20.62055629 35.93868382-20.47326659 11.19401627-40.50466414 23.12448098-60.68335137 34.76036634-43.45045791 25.18653662-87.04820548 50.37307323-134.62277464 77.91624483 4.12411126 1.47289687 6.1861669 1.76747625 7.65906377 2.94579376 54.64447417 39.9155054 114.29679772 49.04746604 176.89491503 24.00821909 62.5981173-25.03924691 102.95549177-72.6138161 110.61455554-139.63062402 9.27925033-81.89306641 1.91476594-164.66987094 3.3876628-247.00480644 0.1472897-4.41869063-1.91476594-6.92261532-5.44971843-8.98467094-25.03924691-14.4343894-49.93120416-28.86877882-77.32708608-44.6287754zM554.71400945 367.2142369c6.03887719 3.68224221 10.16298847 6.03887719 14.13981004 8.39551221 71.2882089 41.24111259 142.42912809 82.62951485 214.01191636 123.42875836 15.46541722 8.83738127 22.09345317 20.47326659 21.94616348 38.14802915-0.44186907 68.19512544-0.1472897 136.39025089-0.14728969 204.58537633 0 5.0078494 0.44186907 9.86840908 0.73644844 15.90728628 3.68224221-1.3256072 5.89158752-2.06205563 8.10093282-2.94579374 64.0710142-29.75251694 102.07175363-79.6837211 108.11063085-149.79361249 6.33345658-72.6138161-22.68261193-130.94053245-84.98614986-169.38314097-62.745407-38.73718787-127.55286961-74.08671296-191.32930443-111.20371428-5.59700814-3.24037312-9.72111939-3.68224221-15.61270692-0.29457938-24.15550879 14.13981003-48.60559698 27.83775099-74.97045109 43.15587853zM216.24230691 270.44491203c-6.62803595-0.88373813-10.60485751 2.20934532-14.72896877 4.27140094-60.97793075 30.63625506-96.62203518 80.12559015-102.21904332 147.87884654-5.74429781 70.25718107 21.50429441 127.9947387 81.15661796 165.70089876 63.92372449 40.35737445 130.64595307 76.44334797 196.04257446 114.44408742 3.82953187 2.20934532 7.36448439 4.12411126 11.78317501 1.47289688 25.33382629-14.72896878 50.66765259-29.45793756 77.47437578-44.92335477-5.59700814-3.38766283-9.42654002-5.89158752-13.40336158-8.24822253-71.2882089-41.24111259-142.42912809-82.62951485-214.01191636-123.28146868-16.05457598-9.13196064-22.53532223-21.06242535-22.38803255-39.32634664 0.58915875-72.31923671 0.29457937-144.7857631 0.29457937-217.98873792z m190.15098694 130.79324274c6.1861669-3.24037312 10.31027814-5.30242877 14.28709973-7.65906375 70.55176044-40.65195383 141.25081059-81.00932829 211.36070197-122.39773056 16.79102442-9.86840908 31.07812413-10.16298847 47.86914854-0.29457937 59.0631648 34.907656 118.56819867 68.78428419 177.92594284 102.95549177 3.5349525 2.06205563 6.48074626 5.89158752 12.51962347 4.12411125 7.80635344-70.10989139-13.40336159-129.32034589-70.69905013-171.73977596-59.50503387-44.18690634-125.34352431-50.22578353-191.03472509-15.6127069-65.98578013 34.907656-129.76221494 74.08671296-194.56967756 111.35100396-3.68224221 2.06205563-7.65906378 3.82953187-7.65906377 9.27925033v89.99399923z m208.41490823 115.9169843c0-20.17868721-0.44186907-36.96971163 0.14728969-53.61344636 0.29457937-7.65906378-2.20934532-12.0777544-8.98467096-15.75999658-29.45793756-16.49644503-58.76858542-33.43475913-87.78465391-50.6676526-5.59700814-3.38766283-9.72111939-3.38766283-15.46541723-0.14728971-29.01606849 17.23289347-58.32671636 34.17120756-87.78465393 50.66765261-6.77532564 3.82953187-8.83738127 8.24822251-8.83738127 15.90728628 0.44186907 32.84560039 0.58915875 65.83849045 0 98.68409082-0.1472897 8.98467097 3.09308345 13.69794096 10.75214722 17.67476253 13.99252034 7.2171947 27.24859225 15.61270692 40.94653321 23.41906036 17.38018317 9.86840908 34.7603663 27.6904613 51.99325978 27.54317163 17.96934191-0.1472897 35.79139413-17.52747284 53.46615667-27.54317163 16.9383141-9.72111939 39.17905696-16.20186565 48.75288666-30.78354473 9.86840908-15.46541722 1.76747625-39.03176725 2.79850407-55.38092262z"
          fill="#d81e06" p-id="19593"></path>
      </svg>
    </el-drawer>
    <LZDialog :dialog-object="dialogObjDelDef" @dialogClose="dialogCloseDef" @dialogSuccess="dialogSuccessDef">
      <div class="ptb16 t-c">删除之后不可复原</div>
    </LZDialog>
    <el-drawer v-model="drawer3" size="40%">
      <ChatGPT></ChatGPT>
    </el-drawer>
  </div>
</template>

<script setup>
import { useUserStore } from '@/stores/userinfo';
import hljs from 'highlight.js';
import 'highlight.js/lib/common';
import 'highlight.js/styles/atom-one-dark.min.css';

import SnowflakeId from 'snowflake-id';
import { onMounted, ref } from 'vue';
import LZDialog from './components/dialog.vue';
import CodingEditor from './components/code.vue';
import ChatGPT from './components/mainComponents/ChatGPT.vue';
const snowflake = new SnowflakeId({
  mid: 42,
  offset: (2024 - 1970) * 31536000 * 1000,
});

// 1.1 引入Vditor 构造函数
import Vditor from 'vditor';
// 1.2 引入样式
import 'vditor/dist/index.css';

//sk-Wza31MksVicYvfMjDLEAMcCP1S3htPXNrB6LYE5peSxB5mWp
function getMdiText(value) {
  return mdi.render(value);
}
function formatDate(dateString) {
  return proxy.$moment(dateString).format('yyyy-MM-DD HH:mm:ss');
}
function getSplitResult(o) {
  console.log('o', o.split('-').length);

  // 检查o.zsd通过'|'分隔符分割后的数组长度
  if (o.split('|').length > 1) {
    // 如果长度大于0，返回第一个元素
    return o.split('|').filter(Boolean);
  } else if (o.split('-').length > 1) {
    // 如果通过'|'分割后的数组长度为0，检查通过'-'分割的数组长度
    // 并返回第一个元素
    console.log("o.zsd.split('-')", o.split('-'));
    return o.split('-').filter(Boolean);
  } else {
    // 如果两次分割后的数组长度都为0，返回原始的o.zsd
    return o;
  }
}

// 引入相关样式
// 删除弹框数据
const dialogObjDelDef = reactive({
  dialogVisible: false,
  title: '是否要删除当前数据？',
  width: '30%',
  successBtnText: '确定',
  closeBtnText: '取消',
  isFooter: true, // 是否显示按钮
});
// 关闭弹窗
const dialogCloseDef = () => {
  dialogObjDelDef.dialogVisible = false;
};
// 确定
const dialogSuccessDef = async () => {
  const result = await proxy.$ax.delete('/4004/api/cs/' + delid.value);
  console.log('result', result);
  delid.value = '';
  loadData();
  ElMessage({
    message: result.status,
    type: 'danger',
    plain: true,
  });
  dialogObjDelDef.dialogVisible = false;
};

const userStore = ref(useUserStore());
const qmessages = ref([
  {
    role: 'system',
    content:
      '\nYou are ChatGPT, a large language model trained by OpenAI.\nKnowledge cutoff: 2023-04\nCurrent model: gpt-4-all\nCurrent time: 2024/1/14 21:51:51\nLatex inline: $x^2$ \nLatex block: $$e=mc^2$$\n\n',
  },
]);
const drawer = ref(false);
const drawer2 = ref(false);
const drawer3 = ref(false);
const { proxy } = getCurrentInstance();
var title = ref('');
var value = ref('');
var aifx = ref('');
var aifx2 = ref('');
var s = ref('');
var titlefx = ref('');
var taglist = ref([]);
var list = ref([]);
var zsdlist = ref([]);
var updateid = ref('');
var delid = ref('');
const loading = ref(true);
var language = ref('javascript');
async function fx() {
  qmessages.value = [
    {
      role: 'system',
      content:
        '\nYou are ChatGPT, a large language model trained by OpenAI.\nKnowledge cutoff: 2023-04\nCurrent model: gpt-4-all\nCurrent time: 2024/1/14 21:51:51\nLatex inline: $x^2$ \nLatex block: $$e=mc^2$$\n\n',
    },
  ];
  await retgpt(
    value.value +
    '。帮我分析这段代à，把有关编程的知识点或者技术点，解析出来形成标签，只返回短语，标题，比如"排序"，"下载"，"数据分析"等，内容用|分割，每个词不超过六个字，请严格按照我说的格式返回',
    titlefx,
  );

  taglist.value = getSplitResult(titlefx.value);
  console.log('titlefx', titlefx);
  console.log('taglist', taglist.value);
}
function tagClose(i) {
  taglist.value.splice(i, 1);
}
function change() {
  qmessages.value = [
    {
      role: 'system',
      content:
        '\n你是一名资深的软件程序工程师，我会输入一些代码，或者让你帮我写出一些代码，请帮我分析这些代码的作用功能以及知识点应用场景，给我优化方案\n\n',
    },
  ];

  if (value.value != '') {
    retgpt2(
      value.value +
      '帮我分析上面的代码，列举出代码中所运用到的技术点或者知识点,用中文回复！,如果有优化的可能，给我优化后的代码，并列举出本段代码的使用场景',
      aifx,
    );
  } else {
    retgpt(title.value + '文字说明尽可能写在代码块里以注释的形式呈现', value);
  }
}
function capitalizeFirstLetter(input) {
  if (!input) return input;
  return input.charAt(0).toUpperCase() + input.slice(1);
}
function getRandomColor() {
  // var color = 'rgb(';
  // for (var i = 0; i < 3; i++) {
  //   var sub = Math.floor(Math.random() * 128); // 生成0-128之间的随机数
  //   color += sub;
  //   if (i < 2) {
  //     color += ',';
  //   } else {
  //     color += ')';
  //   }
  // }
  // return color;

  // 定义颜色代码的数组
  const colorCodes = [
    '#409eff', // primary
    '#67c23a', // success
    '#e6a23c', // warning
    '#f56c6c', // danger & error
    '#909399', // info
  ];

  // 随机选择一个颜色代码
  const randomColorIndex = Math.floor(Math.random() * colorCodes.length);
  const randomColorCode = colorCodes[randomColorIndex];

  return randomColorCode;
}

async function tagfilter(tag) {
  await loadData();
  list.value = list.value.filter((item) => item.zsd.includes(tag));
}
function renderMarkdown(md) {
  Vditor.preview(document.getElementById('vditor'), md, {
    hljs: { style: 'github' },
  });
}
async function retgpt(s, r) {
  qmessages.value.push({
    role: 'user',
    content: s,
  });
  const response = await fetch('/yzam/chat/completions', {
    method: 'POST',
    headers: {
      Authorization: `Bearer sk-Wza31MksVicYvfMjDLEAMcCP1S3htPXNrB6LYE5peSxB5mWp`,
      'Content-Type': 'application/json',
      // 其他需要的头部信息
    },
    body: JSON.stringify({
      messages: qmessages.value,
      model: 'moonshot-v1-8k',
      // presence_penalty: 0,
      stream: true,

      top_p: 1,
      temperature: 0.3,
      presence_penalty: 0.6,
      frequency_penalty: 0,
      // session_id: new Date()
    }),
  });
  console.log('response', response);
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  let currentMessage = '';
  qmessages.value.push({
    role: 'assistant',
    content: currentMessage,
  });
  // console.log(response)
  const reader = response.body.getReader();
  while (true) {
    const { value, done } = await reader.read();

    if (done) {
      console.log('done.');
      // console.log(list);
      console.log('done', r.value);
      loading.value = false;

      break; // 读取完毕
    } else {
      const dataText = new TextDecoder().decode(value);
      const data = dataText.split('\n\n').filter(Boolean);
      // console.log('message: ', new TextDecoder().decode(value));
      // console.log(data);
      // console.log('list', list)
      data.forEach(function (element) {
        // console.log('element', element)
        if (element.startsWith('data: ') && !element.includes('[DONE]')) {
          try {
            const line = JSON.parse(element.replace('data: ', ''));
            // console.log('line', line)
            if (
              line.choices[0].delta.role != 'assistant' &&
              line.choices[0].delta.content != null &&
              line.choices[0].delta.content != ''
            ) {
              currentMessage += line.choices[0].delta.content;
              // console.log('currentMessage', currentMessage)
              r.value = currentMessage;
            }
          } catch (error) {
            console.error('JSON parsing error:', error);
          }
        }
      });

      // list.forEach(function (element) {
      //     if (element.choices[0].delta.role != "assistant" && element.choices[0].delta.content != null) {
      //         that.currentMessage += element.choices[0].delta.content;
      //     }

      // });
      // console.log(that.currentMessage);

      // var data = new TextDecoder().decode(value);
      // this.messages.push(data.data.choices[0].delta.content);
    }
  }
}
async function retgpt2(s, r) {
  qmessages.value.push({
    role: 'user',
    content: s,
  });
  const response = await fetch('/yzam/chat/completions', {
    method: 'POST',
    headers: {
      Authorization: `Bearer sk-Wza31MksVicYvfMjDLEAMcCP1S3htPXNrB6LYE5peSxB5mWp`,
      'Content-Type': 'application/json',
      // 其他需要的头部信息
    },
    body: JSON.stringify({
      messages: qmessages.value,
      model: 'moonshot-v1-8k',
      // presence_penalty: 0,
      stream: true,

      top_p: 1,
      temperature: 0.3,
      presence_penalty: 0.6,
      frequency_penalty: 0,
      // session_id: new Date()
    }),
  });
  console.log('response', response);
  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }
  let currentMessage = '';
  qmessages.value.push({
    role: 'assistant',
    content: currentMessage,
  });
  // console.log(response)
  const reader = response.body.getReader();
  while (true) {
    const { value, done } = await reader.read();

    if (done) {
      console.log('done.');
      // console.log(list);
      console.log('done', r.value);
      loading.value = false;

      break; // 读取完毕
    } else {
      const dataText = new TextDecoder().decode(value);
      const data = dataText.split('\n\n').filter(Boolean);
      // console.log('message: ', new TextDecoder().decode(value));
      // console.log(data);
      // console.log('list', list)
      data.forEach(function (element) {
        // console.log('element', element)
        if (element.startsWith('data: ') && !element.includes('[DONE]')) {
          try {
            const line = JSON.parse(element.replace('data: ', ''));
            // console.log('line', line)
            if (
              line.choices[0].delta.role != 'assistant' &&
              line.choices[0].delta.content != null &&
              line.choices[0].delta.content != ''
            ) {
              currentMessage += line.choices[0].delta.content;
              // console.log('currentMessage', currentMessage)
              r.value = currentMessage;
              contentEditor.value.setValue(aifx.value);
            }
          } catch (error) {
            console.error('JSON parsing error:', error);
          }
        }
      });

      // list.forEach(function (element) {
      //     if (element.choices[0].delta.role != "assistant" && element.choices[0].delta.content != null) {
      //         that.currentMessage += element.choices[0].delta.content;
      //     }

      // });
      // console.log(that.currentMessage);

      // var data = new TextDecoder().decode(value);
      // this.messages.push(data.data.choices[0].delta.content);
    }
  }
}
const contentEditor = ref('');
function opendarwer() {
  contentEditor.value = new Vditor('vditor', {
    height: 360,
    theme: 'dark',
    toolbarConfig: {
      pin: true,
    },
    cache: {
      enable: false,
    },
    after: () => {
      contentEditor.value.setValue(aifx.value);
    },
  });
}
function open() {
  title.value = '';
  value.value = '';
  aifx.value = '';
  titlefx.value = '';
  updateid.value = '';
  delid.value = '';

  drawer.value = true;
}
function openjx(o) {
  aifx2.value = o.jx;

  drawer2.value = true;
}
function openedit(o) {
  updateid.value = o.id;
  title.value = o.title;
  value.value = o.code;
  aifx.value = o.jx;
  titlefx.value = o.zsd;
  taglist.value = getSplitResult(titlefx.value);
  language.value = o.language;

  drawer.value = true;
}
const save = async (event) => {
  if (drawer.value) {
    event.preventDefault(); // 阻止浏览器默认的 Ctrl + S 行为

    if (updateid.value === '') {
      var id = snowflake.generate();
      console.log('id', id);
      var time = new Date();
      titlefx.value = titlefx.value.replace(/-/g, '|');
      var data = {
        id: id,
        time: time,
        title: title.value,
        code: value.value,
        jx: contentEditor.value.getValue(),
        zsd: taglist.value.join('|'),
        language: language.value,
      };
      const result = await proxy.$ax.post('/4004/api/cs', data);
      console.log('result', result);
      if (result.code === 200) {
        loadData();
        drawer.value = false;
        ElMessage({
          message: result.status,
          type: 'success',
          plain: true,
        });
      }
    } else {
      titlefx.value = titlefx.value.replace(/-/g, '|');
      var data = {
        id: updateid.value,
        time: new Date(),
        title: title.value,
        code: value.value,
        jx: contentEditor.value.getValue(),
        zsd: taglist.value.join('|'),
        language: language.value,
      };
      const result = await proxy.$ax.put('/4004/api/cs/' + data.id, data);
      console.log('result', result);
      if (result.code === 200) {
        updateid.value = '';
        loadData();
        drawer.value = false;
        ElMessage({
          message: result.status,
          type: 'success',
          plain: true,
        });
      }
    }
  }
  // 执行保存操作
  console.log('data', data);
};

// 使用 ref 创建一个响应式的引用，用于在模板中访问 save 函数
const saveRef = ref(save);
async function loadData() {
  const result = await proxy.$ax.get('/4004/api/cs');
  console.log('result.value2', result);
  list.value = result.data;
  const zsdValues = result.data.map((item) => item.zsd);

  // 使用join函数将收集到的zsd值用'|'连接起来
  const zsdConcatenated = zsdValues.join('|');

  var zsd = zsdConcatenated.split('|');

  const uniqueArray = Array.from(new Set(zsd));
  zsdlist.value = uniqueArray;
  console.log('list', list.value);
}

loadData();
async function del(id) {
  delid.value = id;
  dialogObjDelDef.dialogVisible = true;
}
async function cp(obj) {
  try {
    // 确保 obj 以及 obj.code 存在
    if (!obj || !obj.code) {
      throw new Error('Invalid object or missing code property');
    }

    // 将字符串复制到剪贴板
    await navigator.clipboard.writeText(obj.code);

    // 成功复制后的通知（可选）
    ElMessage({
      message: '复制成功',
      type: 'success',
      plain: true,
    });
  } catch (err) {
    // 处理错误情况
    console.error('Failed to copy to clipboard:', err);
    ElMessage({
      message: '复制失败' + err,
      type: 'danger',
      plain: true,
    });
  }
}

// 在 setup 阶段，监听全局的 keydown 事件
onMounted(async () => {
  window.addEventListener('keydown', (event) => {
    if (event.ctrlKey && event.key === 's') {
      saveRef.value(event);
    }
  });
});

onUnmounted(() => {
  window.removeEventListener('keydown', saveRef.value);
});
</script>
<style>
.el-drawer__body {
  background-color: #000;
}

.vditor-reset {
  color: #fff !important;
}

.hljs {
  font-size: 10px;
  color: #abb2bf !important;
  word-wrap: break-word !important;
  background: transparent !important;
}

.hljs-doctag,
.hljs-formula,
.hljs-keyword {
  color: #c678dd !important;
}

.hljs-addition,
.hljs-attribute,
.hljs-meta .hljs-string,
.hljs-regexp,
.hljs-string {
  color: #98c379 !important;
}

.hljs-bullet,
.hljs-link,
.hljs-meta,
.hljs-selector-id,
.hljs-symbol,
.hljs-title {
  color: #61aeee !important;
}

/* === removing default button style === */
.button {
  z-index: 99999;
  height: auto;
  padding: 0;
  margin: 0;
  font-family: Arial;
  font-size: var(--fs-size);
  color: transparent;
  text-decoration: none;
  text-transform: uppercase;
  letter-spacing: 3px;
  cursor: pointer;
  background: transparent;
  border: none;
  -webkit-text-stroke: 1px var(--text-stroke-color);

  --border-right: 6px;
  --text-stroke-color: rgb(255 255 255 / 60%);
  --animation-color: #37ff8b;
  --fs-size: 1em;
}

/* this is the text, when you hover on button */
.hover-text {
  position: absolute;
  inset: 0;
  box-sizing: border-box;
  width: 0%;
  overflow: hidden;
  color: var(--animation-color);
  content: attr(data-text);
  border-right: var(--border-right) solid var(--animation-color);
  transition: 0.5s;
  -webkit-text-stroke: 1px var(--animation-color);
}

/* hover */
.button:hover .hover-text {
  width: 100%;
  filter: drop-shadow(0 0 23px var(--animation-color));
}
</style>
<style scoped lang="less">
.masonry {
  column-gap: 30px;
  width: 90%;
  margin: 20px auto;
  columns: 4;

  .item {
    width: 100%;
    break-inside: avoid;
    margin-bottom: 30px;
  }

  h2 {
    padding: 8px 0;
  }
}

@media screen and (width >=1024px) and (width <=1439.98px) {
  .masonry {
    column-gap: 20px;
    width: 90vw;
    columns: 3;
  }
}

@media screen and (width >=768px) and (width <=1023.98px) {
  .masonry {
    column-gap: 20px;
    width: 96vw;
    columns: 2;
  }
}

@media screen and (width <=767.98px) {
  .masonry {
    width: 96vw;
    columns: 1;
  }
}

.card2 {
  position: relative;
  align-items: center;
  justify-content: space-between;
  padding: 20px 10px;
  font-weight: 600;
  color: #fff;
  cursor: pointer;
  background-color: rgb(65 65 65 / 30.8%);
  backdrop-filter: blur(30px);
  border: 1px solid rgb(255 255 255 / 8.9%);
  border-radius: 10px;
}

.abs {
  position: absolute;
  bottom: 2%;
  left: 50%;
  transform: translate(-50%, -50%);
  cursor: pointer;
}

.rotate {
  animation: rotation 5s infinite linear;
}

@keyframes rotation {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}
</style>
